package cn.adelyn.base.auth.dao;

import cn.adelyn.base.auth.dao.mapper.AuthAccountMapper;
import cn.adelyn.base.auth.pojo.bo.AuthAccountBO;
import cn.adelyn.base.auth.pojo.model.AuthAccountModel;
import cn.adelyn.common.core.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Objects;

/**
 * @author chengze
 * @date 2022/12/20
 * @desc AuthAccountDaoService
 */
@Repository
public class AuthAccountDaoService {

    @Autowired
    private AuthAccountMapper authAccountMapper;

    public AuthAccountBO getAuthAccountBOByUserName(String userName) {
        QueryWrapper<AuthAccountModel> queryWrapper = new QueryWrapper();
        queryWrapper.lambda()
                .select(AuthAccountModel::getUserId, AuthAccountModel::getStatus, AuthAccountModel::getPassword, AuthAccountModel::getUserType)
                .eq(AuthAccountModel::getUserName, userName);

        // 账号为空的时候不抛异常，交给上层处理，防止计时攻击
        // 同时避免下面的 cglib 对象拷贝报空指针
        AuthAccountModel authAccountModel = authAccountMapper.selectOne(queryWrapper);
        if (Objects.isNull(authAccountModel)) {
            return null;
        }
        return CglibUtil.copy(authAccountMapper.selectOne(queryWrapper), AuthAccountBO.class);
    }

    public void registerAccount(AuthAccountModel authAccountModel) {
        authAccountMapper.insert(authAccountModel);
    }
}
